//
//  NetworkServicesTableController.m
//  TabulaImaginarius
//
//  Created by TA2 on 3/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "NetworkServicesTableController.h"
#import "NetworkController.h"

@implementation NetworkServicesTableController

@synthesize tableView;

- (void)viewDidLoad {
	[super viewDidLoad];
	[self retain];
	dispatch_queue_t updateQueue = dispatch_queue_create("tableUpdate", NULL);
	
	dispatch_async(updateQueue, ^{		
		while ([NetworkController sharedNetworkController].bonjourIsActive) {
			[self performSelectorOnMainThread:@selector(updateMethod) withObject:nil waitUntilDone:NO];
			usleep(100000);
		}
	});
}

- (void)updateMethod {
	[sessionList reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}
#pragma mark -
#pragma mark View lifecycle

/*
 - (void)viewDidLoad {
 [super viewDidLoad];
 
 // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
 // self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }
 */

/*
 - (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];
 }
 */
/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [Players sharedBonjourPlayers].count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
	// Configure the cell.
	if (((Player *)[[Players sharedBonjourPlayers] objectAtIndex:indexPath.row]).isHost) {
		cell.detailTextLabel.text = [@"Hosting on: " stringByAppendingFormat:((Player *)[[Players sharedBonjourPlayers] objectAtIndex:indexPath.row]).ip];
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	} else {
		cell.detailTextLabel.text = @"Waiting to join session";
		cell.accessoryType = UITableViewCellAccessoryNone;
	}
	cell.textLabel.text = ((Player *)[[Players sharedBonjourPlayers] objectAtIndex:indexPath.row]).alias;
	
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)pressedTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[self tablePressed:tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}

- (void)tableView:(UITableView *)pressedTableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	[self tablePressed:tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}

- (void)tablePressed:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	if (((Player *)[[Players sharedBonjourPlayers] objectAtIndex:indexPath.row]).isHost) {
		/*UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Enter your character name: " message:@"                     \n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
		UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 35.0, 260.0, 25.0)];
		[myTextField setBackgroundColor:[UIColor whiteColor]];
		[myAlertView addSubview:myTextField];
		[myAlertView show];
		[myTextField becomeFirstResponder];
		[myAlertView release];*/
		[superController disableUI];
		dispatch_queue_t connectQueue = dispatch_queue_create("connectToHost", NULL);
		
		dispatch_async(connectQueue, ^{
			for (int waitingTimer = 0; waitingTimer < 1500000; waitingTimer += 1000) {
				usleep(1000);
				if ([NetworkController sharedNetworkController].hasFoundHost) {
					break;
				}
			}
			[self performSelectorOnMainThread:@selector(enableUI) withObject:nil waitUntilDone:NO];
		});
		[[NetworkController sharedNetworkController] joinSession:((Player *)[[Players sharedBonjourPlayers] objectAtIndex:indexPath.row]).ip port:((Player *)[[Players sharedBonjourPlayers] objectAtIndex:indexPath.row]).port];
	}
}

- (void)enableUI {
	[superController enableUI];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
